package com.bw.network_sdk.interceptor;

import com.blankj.utilcode.util.LogUtils;
import com.bw.network_sdk.utils.SignUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Sign拦截器
 * */
public class SignInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
//        StringBuffer buffer = new StringBuffer();
        //获取原有请求中的RequestBody
        RequestBody body = request.body();
        Buffer buffer = new Buffer();
        //将body写入到buffer中
        body.writeTo(buffer);
        //读取buffer中的body写入json字符串
        String jsonStr = buffer.readUtf8();
        //秒杀接口的json格式
        //{"goodsCount": 0,"goodsDesc": "string","goodsIcon": "string","goodsId": 0,"goodsPrice": "string",
        //  "goodsSku": "string","time": 0,"userId": 0}
        //json中{}对应json对象
        //[]对应的json集合
        //接口请求中一般情况下->requestbody
        //由于每个接口中RequestBody中json的key为不固定的key值
        //创建原始JSONObject->解析处理
        LogUtils.e("SignInterceptor"+jsonStr);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(jsonStr);
            //由于每个接口上传的json字符串键值对不同，获取json字符串中key的迭代器->全部key的string
            //值生成迭代器
            Iterator<String>it = jsonObject.keys();
            //遍历迭代器中的key值
            StringBuffer sb = new StringBuffer();
            while (it.hasNext()){
                //从迭代器获取一个key值
                String key = it.next();
                //拼接全部value值
                sb.append(jsonObject.getString(key));
            }
            //通过使用加密的工具类SignUtils.createSign()->生成加密后的sign字符串
            String sign = SignUtils.createSign(sb.toString());
            jsonObject.put("sign",sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //将拼接完sign的新的jsonobject生成为新的requestbody
        RequestBody signBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),
                jsonObject.toString());
        //覆盖掉原有的requestbody
        builder.post(signBody);
        return chain.proceed(builder.build());
    }
}
